package cqrtplm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.ec.module.vo.ChgFormVO;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeService;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.partbom.dto.PartBomTreeNode;
import com.hustcad.plm.pdm.partbom.dto.PartBomView;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartUsageLinkService;
import com.hustcad.plm.pdm.partbom.service.view.TyplmViewDefService;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.part.PartMasterDO;
import com.ty.basic.entity.part.PartUsageLinkDO;
import com.ty.basic.entity.view.ViewDefDO;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.entity.RtChangeaffectAssociatedbomDO;
import cqrtplm.entity.RtChangeaffectEbomDO;
import cqrtplm.entity.RtChangeaffectFinishedbomDO;
import cqrtplm.mapper.RTChangeMapper;
import cqrtplm.mapper.RtChangeaffectAssociatedbomMapper;
import cqrtplm.mapper.RtChangeaffectEbomMapper;
import cqrtplm.mapper.RtChangeaffectFinishedbomMapper;
import cqrtplm.service.BatchModifyBomService;
import cqrtplm.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BatchModifyBomServiceImpl implements BatchModifyBomService {
    private static final int MAX_RETRY = 150; //设置最大重试次数防止死循环
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private RTChangeMapper rtChangeMapper;
    @Resource
    private RtChangeaffectEbomMapper rtChangeaffectEbomMapper;
    @Resource
    private RtChangeaffectFinishedbomMapper rtChangeaffectFinishedbomMapper;
    @Resource
    private RtChangeaffectAssociatedbomMapper rtChangeaffectAssociatedbomMapper;
    @Resource
    private TyplmPartUsageLinkService typlmPartUsageLinkService;
    //设计视图名称
    private final String DESIGN_VIEW_NAME = "Design";
    @Resource
    private TyplmViewDefService typlmViewDefService;
    @Resource
    private TyplmPartBomService typlmPartBomService;
    @Resource
    private TyplmPartService typlmPartService;
    @Resource
    private TyplmAttributeService typlmAttributeService;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;

    public StringBuffer errMsg;

    /**
     * 批量修改BOM结构
     *
     * @param workFlowContainerId
     * @return
     */
    @Transactional
    @Override
    public void batchModifyBom(String workFlowContainerId) {
        try {
            WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(new BigInteger(workFlowContainerId));
            if (!(workFlowContainerView instanceof FlowChgFormView)) {
                return;
            }
            errMsg = new StringBuffer();
            FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
            ChgFormVO chgFormVO = flowChgFormView.getChgFormVO();
            List<PartUsageLinkDO> deleteLinkList = new ArrayList();
            List<JSONObject> addLinkList = new ArrayList();
            Map<String, List<Map<String, String>>> map = getModifyBOM(chgFormVO);
            if (map != null && !map.isEmpty()) {
                for (String type : map.keySet()) {
                    List<Map<String, String>> lists = map.get(type);
                    for (int i = 0; i < lists.size(); i++) {
                        Map<String, String> tempMap = lists.get(i);
                        String changeType = tempMap.get("type");
                        if ("图号升级".equals(changeType)) {
                            String beforeChangeNo = tempMap.get("beforeChangeNo");
                            String afterChangeNo = tempMap.get("afterChangeNo");
                            String count = tempMap.get("count");
                            String bSegmNum = tempMap.get("bSegmNum");
                            String parentNo = tempMap.get("parentNo");
                            getModifyUsageLink(beforeChangeNo, afterChangeNo, parentNo, count, bSegmNum, "", changeType, deleteLinkList, addLinkList);
                        } else if ("删除".equals(changeType)) {
                            String beforeChangeNo = tempMap.get("beforeChangeNo");
                            String count = tempMap.get("count");
                            String bSegmNum = tempMap.get("bSegmNum");
                            String parentNo = tempMap.get("parentNo");
                            getModifyUsageLink(beforeChangeNo, "", parentNo, count, bSegmNum, "", changeType, deleteLinkList, addLinkList);
                        } else if ("增加".equals(changeType)) {
                            String afterChangeNo = tempMap.get("afterChangeNo");
                            String count = tempMap.get("count");
                            String aSegmNum = tempMap.get("aSegmNum");
                            String parentNo = tempMap.get("parentNo");
                            getModifyUsageLink("", afterChangeNo, parentNo, count, "", aSegmNum, changeType, deleteLinkList, addLinkList);
                        } else if ("修改".equals(changeType)) {
                            String beforeChangeNo = tempMap.get("beforeChangeNo");
                            String afterChangeNo = tempMap.get("afterChangeNo");
                            String count = tempMap.get("count");
                            String aSegmNum = tempMap.get("aSegmNum");
                            String bSegmNum = tempMap.get("bSegmNum");
                            String parentNo = tempMap.get("parentNo");
                            getModifyUsageLink(beforeChangeNo, afterChangeNo, parentNo, count, bSegmNum, aSegmNum, changeType, deleteLinkList, addLinkList);
                        }
                    }
//                if ("图号升级".equals(type)) {
//                    for (int i = 0; i < lists.size(); i++) {
//                        Map<String, Object> tempMap = lists.get(i);
//                        String beforeChangeNo = (String) tempMap.get("beforeChangeNo");
//                        String afterChangeNo = (String) tempMap.get("afterChangeNo");
//                        String count = (String) tempMap.get("count");
//                        List<String> ebomNumbers = (List<String>) tempMap.get("ebomNumbers");
//                        List<String> mbomNumbers = (List<String>) tempMap.get("mBomNumbers");
//                        getModifyUsageLink(beforeChangeNo, afterChangeNo, count, ebomNumbers, type, deleteLinkList, addLinkList);
//                        getModifyUsageLink(beforeChangeNo, afterChangeNo, count, mbomNumbers, type, deleteLinkList, addLinkList);
//                    }
//                } else if ("增加".equals(type)) {
//                    for (int i = 0; i < lists.size(); i++) {
//                        Map<String, Object> tempMap = lists.get(i);
//                        String afterChangeNo = (String) tempMap.get("afterChangeNo");
//                        String count = (String) tempMap.get("count");
//                        List<String> bomNumbers = (List<String>) tempMap.get("associatedNumbers");
//                        getModifyUsageLink("", afterChangeNo, count, bomNumbers, type, deleteLinkList, addLinkList);
//                    }
//                } else if ("删除".equals(type)) {
//                    for (int i = 0; i < lists.size(); i++) {
//                        Map<String, Object> tempMap = lists.get(i);
//                        String beforeChangeNo = (String) tempMap.get("beforeChangeNo");
//                        List<String> bomNumbers = (List<String>) tempMap.get("associatedNumbers");
//                        getModifyUsageLink(beforeChangeNo, "", "", bomNumbers, type, deleteLinkList, addLinkList);
//                    }
//                } else if ("替换".equals(type) || "修改".equals(type)) {
//                    for (int i = 0; i < lists.size(); i++) {
//                        Map<String, Object> tempMap = lists.get(i);
//                        String beforeChangeNo = (String) tempMap.get("beforeChangeNo");
//                        String afterChangeNo = (String) tempMap.get("afterChangeNo");
//                        String count = (String) tempMap.get("count");
//                        List<String> bomNumbers = (List<String>) tempMap.get("associatedNumbers");
//                        getModifyUsageLink(beforeChangeNo, afterChangeNo, count, bomNumbers, type, deleteLinkList, addLinkList);
//                    }
//                }
                }
            }
            //执行子件批量删除
            if (deleteLinkList != null && !deleteLinkList.isEmpty()) {
                typlmPartUsageLinkService.batchDeletePartUsageLink(deleteLinkList);
            }
            if (addLinkList != null && !addLinkList.isEmpty()) {
                //获取需要批量创建的link
                List<PartBomView> addPartBomViewList = new ArrayList<>();
                for (int i = 0; i < addLinkList.size(); i++) {
                    JSONObject jsonObject = addLinkList.get(i);
                    getAddPartBomViewList(jsonObject, addPartBomViewList);
                }
                if (addPartBomViewList != null && !addPartBomViewList.isEmpty()) {
                    //执行子件批量添加
                    Map<BigInteger, Long> bigIntegerLongMap = typlmPartBomService.saveBomViewListImmediately(addPartBomViewList);
                    //批量更新BOM行属性
                    updateBomlineAttrs(addPartBomViewList);

                }
            }
        } catch (Exception e) {
            log.error("批量修改BOM异常", e);
            throw RTErrorCodeEnum.UPDATE_BOM_ERROR.getException(e.getMessage());
        }
    }

    /**
     * 批量更新BOM行属性
     */
    private void updateBomlineAttrs(List<PartBomView> addPartBomViewList) {
        if (CollectionUtils.isNotEmpty(addPartBomViewList)) {
            for (PartBomView partBomView : addPartBomViewList) {
                PartBomTreeNode parent = partBomView.getParent();
                List<SaveObjIBADTO> objWithIbaList = new ArrayList<>();
                List<PartBomTreeNode> childrens = partBomView.getBomTreeNodeList();
                for (PartBomTreeNode child : childrens) {
                    List<IbaDTO> objIbaList = buildSaveIbaDTO(child.getIbaAttributeMap());
                    String masterOid = child.getMasteredoid();
                    List<PartUsageLinkDO> partUsageLinkDOS = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(parent.getOid(), new BigInteger(masterOid));
                    if (partUsageLinkDOS == null || partUsageLinkDOS.isEmpty()) {
                        continue;
                    }
                    PartUsageLinkDO partUsageLinkDO = partUsageLinkDOS.get(0);
                    if (CollectionUtils.isNotEmpty(objIbaList)) {
                        SaveObjIBADTO saveObjIBADTO = new SaveObjIBADTO();
                        CTyEntityBaseDO ctyEntityBaseDO = new CTyEntityBaseDO();
                        ctyEntityBaseDO.setOid(partUsageLinkDO.getOid());
                        ctyEntityBaseDO.setOtype(TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
                        saveObjIBADTO.setCTyEntityBaseDO(ctyEntityBaseDO);
                        saveObjIBADTO.setObjIbaList(objIbaList);
                        objWithIbaList.add(saveObjIBADTO);
                    }
                }
                if (CollectionUtils.isNotEmpty(objWithIbaList)) typlmAttributeValueService.batchSaveIBAByObjList(objWithIbaList, false);
            }
        }
    }

    public void getModifyUsageLink(String beforeChangeNo, String afterChangeNo, String parentNo, String countStr, String bSegmNum, String aSegmNum, String type, List<PartUsageLinkDO> deleteLinkList, List<JSONObject> addLinkList) throws Exception {
        if ("图号升级".equals(type)) {
            JSONObject partJson = rtChangeMapper.queryLatestMaterialByCode(parentNo, DESIGN_VIEW_NAME);
            List<PartMasterDO> beforeMasterDOS = typlmPartService.queryPartMasterByPartNumber(beforeChangeNo);
            List<PartMasterDO> afterMasterDOS = typlmPartService.queryPartMasterByPartNumber(afterChangeNo);
            if (ObjectUtils.isNotEmpty(partJson) && CollectionUtils.isNotEmpty(beforeMasterDOS) && CollectionUtils.isNotEmpty(afterMasterDOS)) {
                PartMasterDO beforeMasterDO = beforeMasterDOS.get(0);
                PartMasterDO afterMasterDO = afterMasterDOS.get(0);
                List<PartUsageLinkDO> beforeUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(new BigInteger(partJson.getString("OID")), beforeMasterDO.getOid());
                List<PartUsageLinkDO> afterUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(new BigInteger(partJson.getString("OID")), afterMasterDO.getOid());
                if (beforeUsageLinkList.size() > 0 && afterUsageLinkList.size() == 0) {
                    for (int i = 0; i < beforeUsageLinkList.size(); i++) {
                        PartUsageLinkDO beforeUsageLinkDO = beforeUsageLinkList.get(i);
                        deleteLinkList.add(beforeUsageLinkDO);
                        Double count = beforeUsageLinkDO.getAmount();
                        if (StringUtils.isNotBlank(countStr)) {
                            count = Double.parseDouble(countStr);
                        }
                        Long line = beforeUsageLinkDO.getValue();
                        String SegmNum = this.rtChangeMapper.queryIBAValueByOidAndOtype(beforeUsageLinkDO.getOid().toString(), beforeUsageLinkDO.getOtype(), "SegmNum");
                        SegmNum = CommonUtil.concatSegmNum(SegmNum);
                        if (StringUtils.isBlank(bSegmNum)) bSegmNum = SegmNum;
                        String ManufacturingAttr = this.rtChangeMapper.queryIBAValueByOidAndOtype(beforeUsageLinkDO.getOid().toString(), beforeUsageLinkDO.getOtype(), "ManufacturingAttr");
                        String Position = this.rtChangeMapper.queryIBAValueByOidAndOtype(beforeUsageLinkDO.getOid().toString(), beforeUsageLinkDO.getOtype(), "Position");
                        Map<String, List<String>> ibaMap = typlmAttributeService.getIbaAttributeMap(beforeUsageLinkDO.getOid(), TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("ibaMap", ibaMap);
                        jsonObject.put("count", count);
                        jsonObject.put("lineNumber", line);
                        jsonObject.put("parentPartDO", partJson);
                        jsonObject.put("childPartMasterDO", afterMasterDO);
                        addLinkList.add(jsonObject);
                    }
                }
            }
        } else if ("修改".equals(type) || "替换".equals(type)) {
            JSONObject partJson = rtChangeMapper.queryLatestMaterialByCode(parentNo, DESIGN_VIEW_NAME);
            List<PartMasterDO> beforeMasterDOS = typlmPartService.queryPartMasterByPartNumber(beforeChangeNo);
            List<PartMasterDO> afterMasterDOS = typlmPartService.queryPartMasterByPartNumber(afterChangeNo);
            if (ObjectUtils.isNotEmpty(partJson) && CollectionUtils.isNotEmpty(beforeMasterDOS) && CollectionUtils.isNotEmpty(afterMasterDOS)) {
                PartMasterDO beforeMasterDO = beforeMasterDOS.get(0);
                PartMasterDO afterMasterDO = afterMasterDOS.get(0);
                List<PartUsageLinkDO> beforeUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(new BigInteger(partJson.getString("OID")), beforeMasterDO.getOid());
                List<PartUsageLinkDO> afterUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(new BigInteger(partJson.getString("OID")), afterMasterDO.getOid());
                if (beforeUsageLinkList.size() > 0 && afterUsageLinkList.size() == 0) {
                    for (int i = 0; i < beforeUsageLinkList.size(); i++) {
                        PartUsageLinkDO beforeUsageLinkDO = beforeUsageLinkList.get(i);
                        String SegmNum = this.rtChangeMapper.queryIBAValueByOidAndOtype(beforeUsageLinkDO.getOid().toString(), beforeUsageLinkDO.getOtype(), "SegmNum");
                        SegmNum = CommonUtil.concatSegmNum(SegmNum);
                        Double count = beforeUsageLinkDO.getAmount();
                        if (StringUtils.isNotBlank(countStr)) {
                            count = Double.parseDouble(countStr);
                        }
                        bSegmNum = CommonUtil.concatSegmNum(bSegmNum);
                        aSegmNum = CommonUtil.concatSegmNum(aSegmNum);
                        Long line = beforeUsageLinkDO.getValue();
                        String ManufacturingAttr = this.rtChangeMapper.queryIBAValueByOidAndOtype(beforeUsageLinkDO.getOid().toString(), beforeUsageLinkDO.getOtype(), "ManufacturingAttr");
                        String Position = this.rtChangeMapper.queryIBAValueByOidAndOtype(beforeUsageLinkDO.getOid().toString(), beforeUsageLinkDO.getOtype(), "Position");
                        Map<String, List<String>> ibaMap = typlmAttributeService.getIbaAttributeMap(beforeUsageLinkDO.getOid(), TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
                        if (StringUtils.isNotBlank(bSegmNum)) {
                            //段号不为空，说明指定段号
                            //删除指定段号的BOM
                            if (bSegmNum.equals(SegmNum)) deleteLinkList.add(beforeUsageLinkDO);
                        } else {
                            //未指定段号，删除所有
                            deleteLinkList.add(beforeUsageLinkDO);
                        }
                        if (StringUtils.isNotBlank(aSegmNum)) {
                            ibaMap.put("SegmNum", Arrays.asList(aSegmNum));
                            ibaMap.put("Position", Arrays.asList(Position));
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("ibaMap", ibaMap);
                            jsonObject.put("count", count);
                            jsonObject.put("lineNumber", line);
                            jsonObject.put("parentPartDO", partJson);
                            jsonObject.put("childPartMasterDO", afterMasterDO);
                            addLinkList.add(jsonObject);
                        } else {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("ibaMap", ibaMap);
                            jsonObject.put("count", count);
                            jsonObject.put("lineNumber", line);
                            jsonObject.put("parentPartDO", partJson);
                            jsonObject.put("childPartMasterDO", afterMasterDO);
                            addLinkList.add(jsonObject);
                        }
                    }
                }
            }
        } else if ("删除".equals(type)) {
            JSONObject partJson = rtChangeMapper.queryLatestMaterialByCode(parentNo, DESIGN_VIEW_NAME);
            List<PartMasterDO> beforeMasterDOS = typlmPartService.queryPartMasterByPartNumber(beforeChangeNo);
            if (ObjectUtils.isNotEmpty(partJson) && CollectionUtils.isNotEmpty(beforeMasterDOS)) {
                PartMasterDO beforeMasterDO = beforeMasterDOS.get(0);
                List<PartUsageLinkDO> beforeUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(new BigInteger(partJson.getString("OID")), beforeMasterDO.getOid());
                if (beforeUsageLinkList.size() > 0) {
                    for (int i = 0; i < beforeUsageLinkList.size(); i++) {
                        PartUsageLinkDO beforeUsageLinkDO = beforeUsageLinkList.get(i);
                        String SegmNum = this.rtChangeMapper.queryIBAValueByOidAndOtype(beforeUsageLinkDO.getOid().toString(), beforeUsageLinkDO.getOtype(), "SegmNum");
                        SegmNum = CommonUtil.concatSegmNum(SegmNum);
                        if (StringUtils.isNotBlank(bSegmNum)) {
                            bSegmNum = CommonUtil.concatSegmNum(bSegmNum);
                            if (bSegmNum.equals(SegmNum)) {
                                deleteLinkList.add(beforeUsageLinkDO);
                            }
                        } else {
                            deleteLinkList.add(beforeUsageLinkDO);
                        }
                    }
                }
            }
        } else if ("增加".equals(type)) {
            JSONObject partJson = rtChangeMapper.queryLatestMaterialByCode(parentNo, DESIGN_VIEW_NAME);
            List<PartMasterDO> afterMasterDOS = typlmPartService.queryPartMasterByPartNumber(afterChangeNo);
            if (ObjectUtils.isNotEmpty(partJson) && CollectionUtils.isNotEmpty(afterMasterDOS)) {
                PartMasterDO afterMasterDO = afterMasterDOS.get(0);
                List<PartUsageLinkDO> afterUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(new BigInteger(partJson.getString("OID")), afterMasterDO.getOid());
                Double count = 1D;
                if (afterUsageLinkList.size() == 0) {
                    aSegmNum = CommonUtil.concatSegmNum(aSegmNum);
                    if (StringUtils.isNotBlank(countStr)) {
                        count = Double.parseDouble(countStr);
                    }
                    JSONObject jsonObject = new JSONObject();
                    Map<String, List<String>> ibaMap = new HashMap<>();
                    if (StringUtils.isNotBlank(aSegmNum)) ibaMap.put("SegmNum", Arrays.asList(aSegmNum));
                    jsonObject.put("ibaMap", ibaMap);
                    jsonObject.put("count", count);
                    jsonObject.put("lineNumber", null);
                    jsonObject.put("parentPartDO", partJson);
                    jsonObject.put("childPartMasterDO", afterMasterDO);
                    addLinkList.add(jsonObject);
                }
            }
        }
    }
    //批量修改BOM

    public void getAddPartBomViewList(JSONObject jsonObject, List<PartBomView> addPartBomViewList) throws Exception {
        Object count = jsonObject.get("count");
        Object line = jsonObject.get("lineNumber");
        Map<String, List<String>> ibaMap = (Map<String, List<String>>) jsonObject.get("ibaMap");
        JSONObject partJson = jsonObject.getJSONObject("parentPartDO");
        PartMasterDO afterMasterDO = jsonObject.getObject("childPartMasterDO", PartMasterDO.class);
        PartBomView addPartBomView = new PartBomView();
        PartBomTreeNode parent = new PartBomTreeNode();
        //获取设计视图Oid
        ViewDefDO viewDefDO = typlmViewDefService.getViewByName(DESIGN_VIEW_NAME);
        BigInteger viewOid = viewDefDO.getOid();
        parent.setViewID(viewOid);
        parent.setOid(new BigInteger(partJson.getString("OID")));
        parent.setOtype(partJson.getString("OTYPE"));
        parent.setName(partJson.getString("NAME"));
        addPartBomView.setParent(parent);

        PartBomTreeNode childPartBomTreeNode = new PartBomTreeNode();
        childPartBomTreeNode.setViewID(viewOid);
        childPartBomTreeNode.setOtype("ty.inteplm.part.CTyPart");
        if (count == null) {
            childPartBomTreeNode.setAmount(1d);
        } else {
            childPartBomTreeNode.setAmount((Double) count);
        }
        childPartBomTreeNode.setPartoid(partJson.getString("OID"));
        childPartBomTreeNode.setPartotype(partJson.getString("OTYPE"));
        childPartBomTreeNode.setParentPartNumber(partJson.getString("PARTNUMBER"));
        childPartBomTreeNode.setMasterpartnumber(afterMasterDO.getPartnumber());
        childPartBomTreeNode.setMasteredoid(afterMasterDO.getOid().toString());
        if (line == null) {
            childPartBomTreeNode.setValue(10L);
        } else {
            childPartBomTreeNode.setValue((Long) line);
        }
        childPartBomTreeNode.setViewName(DESIGN_VIEW_NAME);
        childPartBomTreeNode.setAction("add");
        if (ibaMap != null) {
            childPartBomTreeNode.setIbaAttributeMap((Map<String, List<String>>) ibaMap);
        }
        addPartBomView.getBomTreeNodeList().add(childPartBomTreeNode);
        addPartBomViewList.add(addPartBomView);
    }

    //获取需要修改的BOM
    public Map<String, List<Map<String, String>>> getModifyBOM(ChgFormVO chgFormVO) throws Exception {
        String changeNo = chgFormVO.getObjectNumber();
        //受影响的EBOM
        List<RtChangeaffectEbomDO> rtChangeaffectEbomDOS = this.rtChangeaffectEbomMapper.queryByChangeNoAndPartNo(changeNo, "");
        //受影响的成品BOM
        List<RtChangeaffectFinishedbomDO> rtChangeaffectFinishedbomDOS = this.rtChangeaffectFinishedbomMapper.queryByChangeNoAndPartNo(changeNo, "");
        //关联受影响的BOM
        List<RtChangeaffectAssociatedbomDO> rtChangeaffectAssociatedbomDOS = this.rtChangeaffectAssociatedbomMapper.queryByChangeNoAndPartNo(changeNo, "");
        //表单内容
        Map<String, List<Map<String, String>>> tempMap = new HashMap<>();
        List<Map<String, String>> ebomMapList = new ArrayList<>();
        List<Map<String, String>> mbomMapList = new ArrayList<>();
        String formData = chgFormVO.getFormData();
        if (StringUtils.isNotBlank(formData)) {
            JSONObject formDataJson = JSONObject.parseObject(formData);
            JSONArray subform47946 = formDataJson.getJSONArray("subform47946");
            JSONArray subform57714 = formDataJson.getJSONArray("subform57714");
            if (CollectionUtils.isNotEmpty(subform47946)) {
                for (int i = 0; i < subform47946.size(); i++) {
                    String beforeChangeNo = subform47946.getJSONObject(i).getString("input67563");
                    String type = subform47946.getJSONObject(i).get("radio81926").toString();
                    String afterChangeNo = subform47946.getJSONObject(i).getString("radio73127");//radio73127
                    if (StringUtils.isNotBlank(afterChangeNo) && afterChangeNo.contains(",")) {
                        afterChangeNo = afterChangeNo.split(",")[0];
                    }
//                    String count = subform47946.getJSONObject(i).getString("number103708");
                    if ("图号升级".equals(type)) {
                        if (CollectionUtils.isNotEmpty(rtChangeaffectEbomDOS)) {
                            List<RtChangeaffectEbomDO> ebomDOList = rtChangeaffectEbomDOS.stream().filter(item -> beforeChangeNo.equals(item.getPartnumber())).collect(Collectors.toList());
                            for (RtChangeaffectEbomDO item : ebomDOList) {
                                Map<String, String> ebomMap = new HashMap<>();
                                ebomMap.put("beforeChangeNo", beforeChangeNo);
                                ebomMap.put("afterChangeNo", afterChangeNo);
                                ebomMap.put("count", "");
                                ebomMap.put("type", type);
                                ebomMap.put("parentNo", item.getFirstParent());
                                ebomMap.put("bSegmNum", item.getSegmentnumber());
                                ebomMapList.add(ebomMap);
                            }
                        }
                        if (CollectionUtils.isNotEmpty(rtChangeaffectFinishedbomDOS)) {
                            List<RtChangeaffectFinishedbomDO> finishBomList = rtChangeaffectFinishedbomDOS.stream().filter(item -> beforeChangeNo.equals(item.getPartnumber())).collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(finishBomList)) {
                                for (RtChangeaffectFinishedbomDO item : finishBomList) {
                                    Map<String, String> bomMap = new HashMap<>();
                                    String materialCode = item.getMaterialcode();
                                    String colorCode = "";
                                    if ("H".equals(materialCode.charAt(5))) {
                                        colorCode = materialCode.split("-")[1];
                                    } else {
                                        colorCode = materialCode.split("-")[2];
                                    }
                                    bomMap.put("beforeChangeNo", beforeChangeNo + "-" + colorCode);
                                    bomMap.put("afterChangeNo", afterChangeNo + "-" + colorCode);
                                    bomMap.put("count", "");
                                    bomMap.put("type", type);
                                    bomMap.put("parentNo", item.getFirstParent());
                                    bomMap.put("bSegmNum", item.getSegmentnumber());
                                    mbomMapList.add(bomMap);
                                }
                            }
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(subform57714)) {
                for (int i = 0; i < subform57714.size(); i++) {
                    String beforeChangeNo = subform57714.getJSONObject(i).getString("input36063");
                    String type = subform57714.getJSONObject(i).getString("input70284");
                    String afterChangeNo = subform57714.getJSONObject(i).getString("input37516");
                    String count = subform57714.getJSONObject(i).getString("input58662");// number104249
                    String beforeSegmNum = subform57714.getJSONObject(i).getString("input69053");// number104249
                    String afterSegmNum = subform57714.getJSONObject(i).getString("input59564");// number104249
                    List<RtChangeaffectAssociatedbomDO> associatedBOMDOList = null;
                    if ("增加".equals(type)) {
                        if (CollectionUtils.isNotEmpty(rtChangeaffectAssociatedbomDOS)) {
                            associatedBOMDOList = rtChangeaffectAssociatedbomDOS.stream().filter(item -> afterChangeNo.equals(item.getPartnumber())).collect(Collectors.toList());
                            for (RtChangeaffectAssociatedbomDO item : associatedBOMDOList) {
                                String parttype = item.getParttype();
                                String bomtype = item.getBomtype();
                                if ("PatternCode".equals(parttype)) {
                                    if ("EBOM号".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        ebomMapList.add(mbomMap);
                                    }
                                } else if ("MaterialCode".equals(parttype)) {
                                    if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                } else if ("Standard".equals(parttype)) {
                                    if ("EBOM号".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        ebomMapList.add(mbomMap);
                                    } else if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                }
                            }
                        }
                    } else if ("删除".equals(type)) {
                        if (CollectionUtils.isNotEmpty(rtChangeaffectAssociatedbomDOS)) {
                            associatedBOMDOList = rtChangeaffectAssociatedbomDOS.stream().filter(item -> beforeChangeNo.equals(item.getPartnumber())).collect(Collectors.toList());
                            for (RtChangeaffectAssociatedbomDO item : associatedBOMDOList) {
                                String parttype = item.getParttype();
                                String bomtype = item.getBomtype();
                                String materialCode = item.getMaterialCode();
                                if ("PatternCode".equals(parttype)) {
                                    if ("EBOM号".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("type", type);
                                        ebomMapList.add(mbomMap);
                                    } else if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        String colorCode = "";
                                        if ("H".equals(materialCode.charAt(5))) {
                                            colorCode = materialCode.split("-")[1];
                                        } else {
                                            colorCode = materialCode.split("-")[2];
                                        }
                                        mbomMap.put("beforeChangeNo", beforeChangeNo + "-" + colorCode);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                } else if ("MaterialCode".equals(parttype)) {
                                    if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                } else if ("Standard".equals(parttype)) {
                                    if ("EBOM号".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("type", type);
                                        ebomMapList.add(mbomMap);
                                    } else if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                }
                            }
                        }
                    } else if ("替换".equals(type) || "修改".equals(type)) {
                        if (CollectionUtils.isNotEmpty(rtChangeaffectAssociatedbomDOS)) {
                            associatedBOMDOList = rtChangeaffectAssociatedbomDOS.stream().filter(item -> beforeChangeNo.equals(item.getPartnumber())).collect(Collectors.toList());
                            for (RtChangeaffectAssociatedbomDO item : associatedBOMDOList) {
                                String parttype = item.getParttype();
                                String bomtype = item.getBomtype();
                                String materialCode = item.getMaterialCode();
                                if ("PatternCode".equals(parttype)) {
                                    if ("EBOM号".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        ebomMapList.add(mbomMap);
                                    } else if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        String colorCode = "";
                                        if ("H".equals(materialCode.charAt(5))) {
                                            colorCode = materialCode.split("-")[1];
                                        } else {
                                            colorCode = materialCode.split("-")[2];
                                        }
                                        mbomMap.put("beforeChangeNo", beforeChangeNo + "-" + colorCode);
                                        mbomMap.put("afterChangeNo", afterChangeNo + "-" + colorCode);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                } else if ("MaterialCode".equals(parttype)) {
                                    if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                } else if ("Standard".equals(parttype)) {
                                    if ("EBOM号".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        ebomMapList.add(mbomMap);
                                    } else if ("成品码".equals(bomtype)) {
                                        Map<String, String> mbomMap = new HashMap<>();
                                        mbomMap.put("beforeChangeNo", beforeChangeNo);
                                        mbomMap.put("afterChangeNo", afterChangeNo);
                                        mbomMap.put("count", count);
                                        mbomMap.put("parentNo", item.getFirstParent());
                                        mbomMap.put("bSegmNum", beforeSegmNum);
                                        mbomMap.put("aSegmNum", afterSegmNum);
                                        mbomMap.put("type", type);
                                        mbomMapList.add(mbomMap);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            tempMap.put("ebomList", ebomMapList);
            tempMap.put("mbomList", mbomMapList);
        }
        return tempMap;
    }

    public List<IbaDTO> buildSaveIbaDTO(Map<String, List<String>> ibaMap) {
        List<IbaDTO> bomLinkIbaAttrs = new ArrayList<>();
        if (ibaMap != null) {
            for (String key : ibaMap.keySet()) {
                List<String> value = ibaMap.get(key);
                if (CollectionUtils.isNotEmpty(value)) {
                    IbaDTO ibadto = new IbaDTO();
                    ibadto.setKey(key);
                    ibadto.setValue(value.get(0));
                    bomLinkIbaAttrs.add(ibadto);
                }
            }
        }
        return bomLinkIbaAttrs;
    }
}
